/**
 * Created by lby on 2018/5/13.
 */

(function() {

    var $ZTreePlus = function(id, url) {
        this.id = id;
        this.url = url;
        this.onClick = null;
        this.settings = null;
        this.ondblclick=null;
    };

    $ZTreePlus.prototype = {
        /**
         * 初始化ztree的设置
         */
        initSetting : function(type) {
            var settings;
            if(type == 0)
            {
                settings = {
                    view : {
                        dblClickExpand : true,
                        selectedMulti : false
                    },
                    data : {simpleData : {enable : true}},
                    callback : {
                        onClick : this.onClick,
                    }
                };
            }
            else if(type == 1)
            {
                settings = {
                    view : {
                        dblClickExpand : true,
                        selectedMulti : false
                    },
                    data : {simpleData : {enable : true, idKey:"code", pIdKey:"pcode", rootPId:"0"}},
                    callback : {
                        onClick : this.onClick,
                    }
                };
            }
            else if(type == 2)
            {
                settings = {
                    check: {
                        enable: true,
                        chkboxType: { "Y": "ps", "N": "ps" }
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    }
                };
            }
            return settings;
        },
        
        /**
         * 加载节点
         */
        loadNodes : function() {
            var treeNodes = null;
            $.ajax({
                async : false,
                type: 'POST',
                dataType : "json",
                url: this.url,//请求的action路径
                error: function () {//请求失败处理函数
                    parent.layer.msg("请求失败");
                },
                success:function(data){ //请求成功后处理函数。
                    treeNodes = data;   //把后台封装好的简单Json格式赋给treeNodes
                }
            });
            return treeNodes;
        },

        /**
         * 初始化ztree
         */
        init : function(type) {
            var zSetting = this.initSetting(type);
            var zNodes = this.loadNodes();
            $.fn.zTree.init($("#" + this.id), zSetting, zNodes);
        },

        /**
         * 绑定onclick事件
         */
        bindOnClick : function(func) {
            this.onClick = func;
        },

        /**
         * 获取选中的值
         */
        getSelectedVal : function(){
            var zTree = $.fn.zTree.getZTreeObj(this.id);
            var nodes = zTree.getSelectedNodes();
            return nodes[0].name;
        }
    };

    window.$ZTreePlus = $ZTreePlus;

}());
